package org.budo.filestore.upyun.uss;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.budo.filestore.api.DeleteResponse;
import org.budo.filestore.api.DownloadRequest;
import org.budo.filestore.api.UploadRequest;
import org.budo.filestore.api.UploadResponse;
import org.budo.filestore.impl.DefaultDeleteResponse;
import org.budo.filestore.impl.DefaultUploadResponse;
import org.budo.support.lang.util.IoUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author lmw
 */
public class UpyunUssFileStore extends AbstractUpyunUssFileStore {
    private static final Logger log = LoggerFactory.getLogger(UpyunUssFileStore.class);

    @Override
    public UploadResponse upload(UploadRequest request) {
        try {
            byte[] bytes = IoUtil.toByteArray(request.getInputStream());
            boolean success = this.getUpYun().writeFile(request.getContentUrl(), bytes);
            return new DefaultUploadResponse(success);
        } catch (Throwable e) {
            log.error("#29 upload error, e=" + e, e);
            return new DefaultUploadResponse(false);
        }
    }

    @Override
    public InputStream downloadStream(DownloadRequest request) {
        String fileBody = this.getUpYun().readFile(request.getContentUrl());
        return new ByteArrayInputStream(fileBody.getBytes());
    }

    @Override
    public DeleteResponse delete(DownloadRequest request) {
        boolean success = this.getUpYun().deleteFile(request.getContentUrl());
        return new DefaultDeleteResponse(success);
    }
}